package cn.sunxiansheng.redis.controller;

import cn.sunxiansheng.redis.utils.RHash;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/rhash")
public class RHashController {

    private final RHash rHash;

    public RHashController(RHash rHash) {
        this.rHash = rHash;
    }

    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    public static class User {
        private Long id;
        private String name;
        private Integer age;
    }

    /**
     * 设置单个hash值
     */
    @PostMapping("/put")
    public void put(@RequestParam String key, @RequestParam String hashKey, @RequestBody User user) {
        rHash.put(key, hashKey, user);
    }

    /**
     * 设置多个hash值
     */
    @PostMapping("/putAll")
    public void putAll(@RequestParam String key, @RequestBody Map<String, User> userMap) {
        rHash.putAll(key, userMap);
    }

    /**
     * 删除hash中的多个值
     */
    @DeleteMapping("/deleteMultiple")
    public Long deleteMultiple(@RequestParam String key, @RequestBody List<String> hashKeys) {
        return rHash.delete(key, hashKeys);
    }

    /**
     * 删除hash中的单个值
     */
    @DeleteMapping("/deleteSingle")
    public Long deleteSingle(@RequestParam String key, @RequestParam String hashKey) {
        return rHash.delete(key, hashKey);
    }

    /**
     * 获取单个hash值并转换为指定类型
     */
    @GetMapping("/getOne")
    public User getOneMapValue(@RequestParam String key, @RequestParam String hashKey) {
        return rHash.getOneMapValue(key, hashKey, User.class);
    }

    /**
     * 获取多个hash值并转换为指定类型
     */
    @GetMapping("/getMulti")
    public List<User> getMultiMapValue(@RequestParam String key, @RequestBody List<String> hashKeys) {
        return rHash.getMultiMapValue(key, hashKeys, User.class);
    }

    /**
     * 获取所有键值对并转换为指定类型
     */
    @GetMapping("/getAll")
    public Map<String, User> getAll(@RequestParam String key) {
        return rHash.getAll(key, User.class);
    }

    /**
     * 判断hash中是否存在某个键
     */
    @GetMapping("/hasHashKey")
    public Boolean hasHashKey(@RequestParam String key, @RequestParam String hashKey) {
        return rHash.hasHashKey(key, hashKey);
    }
}

